from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

X,y = make_blobs(n_samples=200,n_features=2,
                 centers=4,cluster_std=1,
                 center_box=(-10,10),shuffle=True,
                 random_state=1)

plt.figure(figsize=(6,4),dpi=70)
plt.xticks(())
plt.yticks(())
plt.scatter(X[:,0],X[:,1],s=20,marker='o')
plt.show()

n_clusters = 3
kmean = KMeans(n_clusters=n_clusters)
kmean.fit(X)
print('\nkmean:k={},cost={}'.format(n_clusters,int(kmean.score(X))))
#KMeans.score()函数计算k-均值算法你和后的成本，用复数表示，绝对值越大，成本越高
#k-均值算法成本的物理意义为训练样例到其所属的聚类中心点距离的平均值
labels = kmean.labels_#分类后的样本的标注
centers = kmean.cluster_centers_#聚类中心
markers = ['o','^','*']
colors = ['r','b','y']

plt.figure(figsize=(6,4),dpi=80)
plt.xticks(())
plt.yticks(())
#画出样本
for c in range(n_clusters):
    cluster = X[labels == c]
    plt.scatter(cluster[:,0],cluster[:,1],marker=markers[c],c=colors[c],s=20)
#画出中心点
plt.scatter(centers[:,0],centers[:,1],marker='o',c='b',alpha=0.9,s=300)
for i,c in enumerate(centers):
    plt.scatter(c[0],c[1],marker='$%d$'%i,s=50,c=colors[i])
plt.show()

#选择k=2,3,4三种不同的聚类个数
def fit_plot_kmean_model(n_clusters, X):
    plt.xticks(())
    plt.yticks(())

    # 使用 k-均值算法进行拟合
    kmean = KMeans(n_clusters=n_clusters)
    kmean.fit_predict(X)

    labels = kmean.labels_
    centers = kmean.cluster_centers_
    markers = ['o', '^', '*', 's']
    colors = ['r', 'b', 'y', 'k']

    # 计算成本
    score = kmean.score(X)
    plt.title("k={}, score={}".format(n_clusters, (int)(score)))

    # 画样本
    for c in range(n_clusters):
        cluster = X[labels == c]
        plt.scatter(cluster[:, 0], cluster[:, 1], 
                    marker=markers[c], s=20, c=colors[c])
    # 画出中心点
    plt.scatter(centers[:, 0], centers[:, 1],
                marker='o', c="white", alpha=0.9, s=300)
    for i, c in enumerate(centers):
        plt.scatter(c[0], c[1], marker='$%d$' % i, s=50, c=colors[i])

n_clusters = [2,3,4]
plt.figure(figsize=(10,3),dpi=80)
for i,c in enumerate(n_clusters):
    plt.subplot(1,3,i+1)
    fit_plot_kmean_model(c,X)
plt.show()


